package com.nervenets.web.controller.handler.user.wealth;

import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.NumberUtil;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.*;
import com.nervenets.web.hibernate.domain.setting.Tags;
import com.nervenets.web.hibernate.domain.user.Bank;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.rabbitmq.FlowMessage;
import com.nervenets.web.redis.domain.global.GlobalRule;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

public class UserBankWithdrawHandler extends Handler<UserBankWithdrawParams> {
    @Override
    public String handle(UserBankWithdrawParams params, HttpServletRequest request) throws Exception {
        if (!globalVariablesService.canProceed(params.getUserId())) return errorMessage(MessageCode.code_505);

        User user = userDao.findById(params.getUserId(), User.class);
        if (null == user) return errorMessage(MessageCode.code_778);

        final Bank bank = userDao.findById(params.getBankId(), Bank.class);
        if (null == bank) return errorMessage(MessageCode.code_404, "银行账户不存在");

        return (String) redisSyncLocker.keyLock(String.format(Global.Constants.REDIS_USER_WEALTH_LOCK, params.getUserId()), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                long surplus = globalService.getUserWealthOfMoney(params.getUserId(), WealthType.money);
                if (surplus < params.getMoney()) return errorMessage(MessageCode.code_444, "余额不足");

                final GlobalRule globalRule = globalVariablesService.getGlobalRule();
                BigDecimal proportionOfFee = globalRule.getProportionOfUserWithdraw();

                /*if (user.getRole().isDealer()) {
                    proportionOfFee = globalRule.getProportionOfDealerWithdraw();
                }
                if (user.getRole().isMarket()) {
                    proportionOfFee = globalRule.getProportionOfMarketWithdraw();
                }
                if (user.getRole().isIssue()) {
                    proportionOfFee = globalRule.getProportionOfIssueWithdraw();
                }*/

                final long fee = proportionOfFee.multiply(BigDecimal.valueOf(params.getMoney())).longValue();
                final long realWithdrawMoney = params.getMoney() - fee;

                final Tags tag = userDao.findById(bank.getTagId(), Tags.class);
                final String substring = bank.getNumber().substring(bank.getNumber().length() - 4);
                long unionId = JodaUtils.getTimestamp() + NumberUtil.randomNumber(1000, 9999);//生成提现关联ID
                messageProducer.flow(FlowMessage.wealthChange(params.getUserId(), getIp(request), UnionType.normal, unionId, -fee, OperateType.withdrawFee, PayType.surplus, FlowStatus.success, String.format("提现到%s(%s)手续费", tag.getName(), substring)));
                messageProducer.flow(FlowMessage.wealthChange(params.getUserId(), getIp(request), UnionType.normal, unionId, -realWithdrawMoney, OperateType.withdraw, PayType.surplus, FlowStatus.handling, String.format("提现到%s(%s)", tag.getName(), substring)));

                return successMessage(surplus - params.getMoney());
            }
        }, 0);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
